(function(angular) {
	"use strict";
	angular.module("fs.waf").controller("cls.popup.loanView.viewController", viewController);
	viewController.$inject = [ "$scope", "$q", "dialogsModule", "$uibModalInstance", "modalService", "gridService", "layoutConfig", "validatorConfig", "authService", "arithService", "formatService", "dateService", "settlementSummaryService", "settlementPaymentService", "$filter", "glEntryService", "loanInterestService", "loanPastdueService", "loanService"];
	function viewController($scope, $q, dialogsModule, $uibModalInstance, modalService, gridService, layoutConfig, validatorConfig, authService, arithService, formatService, dateService, settlementSummaryService, settlementPaymentService, $filter, glEntryService, loanInterestService, loanPastdueService, loanService) {
		var ctrl = this, errorMessage = {}, settlement = {}, loan = {};
		ctrl.dialogsModule = dialogsModule;
		ctrl.validatorConfig = validatorConfig;
		ctrl.spreadTierInnerGridOptions = {};
		ctrl.loanIntSpreadTier2Column = {};
		ctrl.loanIntRateTypeOptions = [];
		ctrl.setlDetailsConfig = layoutConfig.formConfigs.setlDetailView.tableConfigs.setlDetails.columnDefs;
		ctrl.isDetailsPay = function(item){
			return settlementSummaryService.isDetailsPay(item);
		};
		
		ctrl.isDetailsReceive = function(item){
			return settlementSummaryService.isDetailsReceive(item);
		};
		
		ctrl.init = function() {	
			ctrl.txnSetlInsts = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.txnSetlInsts.tableConfigs.txnSetlInsts, null);
			ctrl.txnSetlInsts.data = "vm.settlement.txnSetlInsts";
			ctrl.txnSetlInsts.enableRowHeaderSelection = false;
			
			/*****************Past Due*******************/
			ctrl.pastdueInnerGridOptions = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.pastdueSchd.tableConfigs.table, null);
			ctrl.pastdueInnerGridOptions.data = "vm.loan.loanPsd.pastdueSchdList";
			
			ctrl.custTierInnerGridOptions = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.pastdueCustTier.tableConfigs.table, null);
			ctrl.custTierInnerGridOptions.data = "vm.loan.loanPsd.tierBaseRateCusts";
			
			ctrl.mixTierInnerGridOptions = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.pastdueMixTier.tableConfigs.table, null);
			ctrl.mixTierInnerGridOptions.data = "vm.loan.loanPsd.tierBaseRateMixs";
			
			/*****************Past Due*******************/
			ctrl.paidLoanTableConfig = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.paidLoans.tableConfigs.paidLoans, null);
			ctrl.paidLoanTableConfig.data = "vm.loan.loanPaidLoans";
			
			ctrl.paidCustpayTableConfig = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.paidCustpays.tableConfigs.paidCustpays, null);
			ctrl.paidCustpayTableConfig.data = "vm.loan.loanPaidCustpays";
			
			var defer1 = $q.defer(), defer2 = $q.defer(), defer3 = $q.defer();
			loanService.getLoanUpdateOptions().then(function(initData) {
				angular.merge(loan, initData);
				ctrl.intCatLabel = loanInterestService.initIntCatLabel(loan.intCatOptions);
				defer1.resolve();
			});
			settlementSummaryService.getFxRateTypes().then(function(fxRateTypes){
				settlement.fxRateTypes = fxRateTypes;
				defer2.resolve();
			});
			settlementPaymentService.settlementPaymentOptions().then(function(map) {
				settlement.deliveryTypeOptions = map.deliveryTypeOptions;
				settlement.currencyOptions = map.currencyOptions;
				settlement.allPartyTypeOptions = map.partyTypeOptions;
				settlement.swiftCaseList = map.swiftCaseList;
				defer3.resolve();
			});
			($q.all({
				defer1 : defer1.promise,
				defer2 : defer2.promise,
				defer3 : defer3.promise
			})).then(function(){
				authService.viewInit(ctrl.dialogsModule.params).then(function(response) {
					if (response.data) {
						settlement = angular.merge(settlement, response.data);
						ctrl.isRollover = settlementSummaryService.isRollover(settlement);
						processTxnSetlInsts(settlement);
						getGlEntryList(ctrl, settlement);
						angular.extend(ctrl, settlementPaymentService.getPayDetailsConfig(settlement, layoutConfig));
						settlementSummaryService.initData(settlement);
						ctrl.payPartyConfig = settlementPaymentService.initData(settlement, layoutConfig);
						//loan
						loan = angular.merge(loan, settlement.loan);
						loanService.getProdCodeChangedData({
							"prodCode" : loan.loanInfo.prodCode
						}).then(function(prodCodeChangedData) {
							loan.ccyOptions = prodCodeChangedData.ccyOptions;
							loan.assetTypeOptions = prodCodeChangedData.assetTypeOptions;
							loan.loanInfo.prodType = prodCodeChangedData.prodType;
							loan.loanInfo.prodSubtype = prodCodeChangedData.prodSubType;
							loan.loanInfo.product = prodCodeChangedData.product;
						});
						loanInterestService.initLoanIntObject(loan);
						loanInterestService.setLoanInfoToInterest(loan);
						initInterestTable(loan);
						var _ctrl = loanInterestService.initTierCriteria(loan, loan.loanIntSpreadTierTypeOptionsBackUp, ctrl.spreadTierInnerGridOptions, ctrl.selectedSpreadTiers);
						angular.merge(ctrl, _ctrl);
						loanCcyChanged(loan);
						loanService.generalMaturityDateChanged(loan);
						loanPastdueService.pastDueIntBaseTypeChanged(loan);
						settlementSummaryService.processLoanPaidLoans(loan.loanPaidLoans);
						settlementSummaryService.processLoanPaidCustpays(loan.loanPaidCustpays);
						//reset pastdueTenorFrom
						if(loan.loanPsd && loan.loanPsd.pastdueSchdList){
							var pastdueTenorFrom =1;
							angular.forEach(loan.loanPsd.pastdueSchdList, function(pastdue, index) {
								pastdue.pastdueTenorFrom = pastdueTenorFrom;
								pastdueTenorFrom = arithService.add(pastdue.pastdueTenor, 1);
							});
						}
						ctrl.layoutConfig = layoutConfig;
						ctrl.loan = loan;
						ctrl.settlement = settlement;
					}
				});
			});
		};
		
		function getGlEntryList(ctrl, settlement){
			glEntryService.getGlentryList($scope, layoutConfig, settlement.settlementInfo.parentId, "CLS:" + settlement.settlementInfo.parentType).then(function(response){
				ctrl.glEntryListConfig = response.glEntryListConfig;
				ctrl.glEntryList = response.glEntryList;
			});
		};
		
		function processTxnSetlInsts(settlement){
			if(settlement.txnSetlInsts){
				angular.forEach(settlement.txnSetlInsts, function(data, index, array){
					data.paycodeName = data.paycode ? data.paycode.substr(7) : "";
					data.itemType_desc = $filter("translate")("label.settlement.init." + data.itemType.toLowerCase());
				});
			}
		}
		
		/**
		 * button
		 */
		ctrl.paymentHistory = function(){
			modalService.openCustomDialogs({
			   "title": "popup.title.paymenthistroy",
			   "dialogsModule" : "cls.loan.repaymentList",
			   "size" : [1300, 300],
			   "params": {
				   "loanId" : $filter("encode")(ctrl.loan.loanInfo.loanId)
			   },
			   "btnCallback" : {
					"ok" : function() {
					}
				}	
			});
		};
		
		ctrl.amendmentHistory = function(){
			modalService.openCustomDialogs({
			   "title": "popup.title.viewamendmentlist",
			   "dialogsModule" : "cls.loan.amendmentList",
			   "size" : [1300, 300],
			   "params": {
				   "loanId" : $filter("encode")(ctrl.loan.loanInfo.loanId)
			   },
			   "btnCallback" : {
					"ok" : function() {
					}
				}	
			});
		};
		
		ctrl.accrualAmortization = function(){
			modalService.openCustomDialogs({
			   "title": "popup.title.intaccruallist",
			   "dialogsModule" : "cls.loan.intAccrualList",
			   "size" : [1300, 300],
			   "params": {
				   "loanId" : $filter("encode")(ctrl.loan.loanInfo.loanId)
			   },
			   "btnCallback" : {
					"ok" : function() {
					}
				}	
			});
		};
		
		ctrl.viewglentry = function(){
			modalService.openCustomDialogs({
			   "title": "popup.loan.glentrylist",
			   "dialogsModule" : "cls.loan.glEntryList",
			   "size" : [900, 400],
			   "params": {
				   "refTxnId" : $filter("encode")(ctrl.loan.loanInfo.loanId),
				   "refTxnType" : "CLS:ISSUE"
			   },
			   "btnCallback" : {
					"ok" : function() {
					}
				}	
			});
		};
		
		ctrl.viewFee = function(){
			modalService.openCustomDialogs({
			   "title": "popup.title.txnfeelist",
			   "dialogsModule" : "cls.loan.txnFeeList",
			   "size" : [1300, 300],
			   "params": {
				   "txnId" : $filter("encode")(ctrl.loan.loanInfo.loanId)
			   },
			   "btnCallback" : {
					"ok" : function() {
					}
				}	
			});
		};
		
		ctrl.loanJournal = function(){
			modalService.openCustomDialogs({
			   "title": "popup.title.txnjournallist",
			   "dialogsModule" : "cls.loan.txnJournalList",
			   "size" : [875, 300],
			   "params": {
				   "txnId" : $filter("encode")(ctrl.loan.loanInfo.loanId),
				   "txnType" : "ISSUE"
			   },
			   "btnCallback" : {
					"ok" : function() {
					}
				}	
			});
		};
		
		ctrl.loanIdLink = function(currRow){
			modalService.openCustomDialogs({
				"title" : "popup.title.loanview",
				"dialogsModule" : "cls.loan.view",
				"params" : {"loanId" : currRow.loanId},
				"size" : [1300, 500],
				"btnCallback" : {
					"ok" : function(obj) {
					}
				}
			});
		};
		ctrl.paidloanIdLink = function(currRow){
			modalService.openCustomDialogs({
				"title" : "popup.title.loanview",
				"dialogsModule" : "cls.loan.view",
				"params" : {"loanId" : currRow.paidloanId},
				"size" : [1300, 500],
				"btnCallback" : {
					"ok" : function(obj) {
					}
				}
			});
		};
		ctrl.repayIdLink = function(currRow){
			modalService.openCustomDialogs({
				"title" : "popup.title.repaymentview",
				"dialogsModule" : "cls.loan.repaymentView",
				"params" : {"repayId" : currRow.repayId},
				"size" : [1300, 500],
				"btnCallback" : {
					"ok" : function(obj) {
					}
				}
			});
		};
		ctrl.custpayIdLink = function(currRow){
			modalService.openCustomDialogs({
				"title" : "popup.title.custpayview",
				"dialogsModule" : "cls.custpay.view",
				"params" : {"custpayId" : currRow.custpayId},
				"size" : [1300, 500],
				"btnCallback" : {
					"ok" : function(obj) {
					}
				}
			});
		};
		
		ctrl.save = function() {
			var messages = [];
			angular.forEach(errorMessage, function(field) {
				angular.forEach(field, function(rule) {
					messages.push(rule);
				});
			});
			if (messages.length > 0) {
				modalService.openErrorDialogs({
					"messages" : messages
				});
			} else {
				return authService.updateSaved(ctrl.loan).then(submitSuccessful, submitFailed);
			}
		};
		
		ctrl.settlement = function() {
			var messages = [];
			angular.forEach(errorMessage, function(field) {
				angular.forEach(field, function(rule) {
					messages.push(rule);
				});
			});
			if (messages.length > 0) {
				modalService.openErrorDialogs({
					"messages" : messages
				});
			} else {
				return authService.updateSubmitted(ctrl.loan).then(submitSuccessful, submitFailed);
			}
		};
		
		ctrl.cancel = function() {
			modalService.openConfirmDialogs({
				"messages" : [ {msg : "title.dialog.confirm.cancel", args : [ctrl.loan.primaryKey]} ],
				"btnCallback" : {
					"ok" : function() {
						authService.updateCancelled(ctrl.loan).then(cancelSuccessful, cancelFailed);
					}
				}
			});
		};
		
		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				"messages" : [ "title.dialog.successful.submit" ],
				"btnCallback" : {
					"close" : function() {
						$scope.go("cls.workflow.wfTxn.list");
					}
				},
				"redirections" : [ {
					"name" : "title.infobar.workflow.list",
					"state" : "cls.workflow.wfTxn.list",
					"params" : {}
				}]
			});
		}

		function submitFailed(response) {
			modalService.openErrorDialogs({
				"messages" : response.error
			});
		}
		
		function cancelSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				"messages" : [ "title.dialog.successful.cancel" ],
				"btnCallback" : {
					"close" : function() {
						$scope.go("cls.workflow.wfTxn.list");
					}
				},
				"redirections" : [ {
					"name" : "title.infobar.workflow.list",
					"state" : "cls.workflow.wfTxn.list",
					"params" : {}
				}]
			});
		}

		function cancelFailed(response) {
			modalService.openErrorDialogs({
				"messages" : response.error
			});
		}
		ctrl.loanIntSpreadTierType2Changed = function(param, form, firstLoad) {
			ctrl.loanIntSpreadTierTypeOptions = loanInterestService.loanIntSpreadTierType2Changed(ctrl.loan, param, firstLoad, ctrl.spreadTierInnerGridOptions, ctrl.loanIntSpreadTier2Column);
		};
		
		ctrl.loanIntCalcMethodChanged = function(itemInterest) {
			if (!itemInterest || !itemInterest.intCat)
				return;
			ctrl.loanIntRateTypeOptions[itemInterest.intCat] = loanInterestService.loanIntCalcMethodChanged(ctrl.loan, itemInterest);
		};
		
		ctrl.loanIntSpreadTierTypeChangedFunctions = function(itemInterest, form, firstLoad) {
			ctrl.loanIntSpreadTierType2Options = loanInterestService.loanIntSpreadTierTypeChangedFunctions(ctrl.loan, itemInterest, firstLoad, ctrl.spreadTierInnerGridOptions);
		};

		ctrl.interestIndexRefChanged = function(itemInterest, form, fisrtLoad) {
			loanInterestService.updateInterestToLoanInfo(ctrl.loan, itemInterest);
		};

		ctrl.getIntRateTypes = function(itemInterest) {
			if (!ctrl.interestGeneral1Layout) {
				var layout = angular.copy(ctrl.layoutConfig.formConfigs.interestGeneral1);
				layout.gridConfigs.intRateType.options.data = "vm.loanIntRateTypeOptions['" + itemInterest.intCat + "']";
				ctrl.interestGeneral1Layout = layout;
			}
			return ctrl.interestGeneral1Layout;
		};
		
		/*************Past Due*****************/
		ctrl.custTierMoreDataDyna = function(obj) {
			loanPastdueService.custTierMoreDataDyna(obj);
		};

		/*************Past Due*****************/
		function loanCcyChanged(loan) {
			if (loan.loanInfo.loanCcy) {
				loanPastdueService.resetIntRateIndexOptions(loan);
			}
			loanInterestService.setLoanInfoToInterest(loan);
		};
		
		ctrl.billIntFlagChanged = function() {
			if (ctrl.loan.loanBill && ctrl.loan.loanBill.billIntFlag != "Y") {
				ctrl.loan.loanBill.billIntWithPrinc = "N";
			}
		};

		// init interest tab"s table
		function initInterestTable(loan) {
			if (loan.loanInts) {
				angular.forEach(loan.loanInts, function(loanInt) {
					var intCat = loanInt.intCat;
					// init spreadTierList
					ctrl.spreadTierInnerGridOptions[intCat] = gridService.createInnerGridOptions($scope, angular.copy(layoutConfig.formConfigs.interestSpreadTier.tableConfigs.table), function(
							eventRow, selectedRows) {
						ctrl.selectedSpreadTiers[intCat] = selectedRows;
					});
					ctrl.spreadTierInnerGridOptions[intCat].data = loanInt.spreadTierList;
					// init tierCriterias
					ctrl.custTierInnerGridOptions[intCat] = gridService.createInnerGridOptions($scope, angular.copy(layoutConfig.formConfigs.custTier.tableConfigs.table));
					ctrl.custTierInnerGridOptions[intCat].data = loanInt.tierBaseRateCusts;
					// init tierCriterias
					ctrl.mixTierInnerGridOptions[intCat] = gridService.createInnerGridOptions($scope, angular.copy(layoutConfig.formConfigs.mixTier.tableConfigs.table));
					ctrl.mixTierInnerGridOptions[intCat].data = loanInt.tierBaseRateMixs;
				});
			}
		}
		
		//settlement payment
		ctrl.swiftTypeCallBack = function(result){
			settlementPaymentService.swiftTypeCallBack(ctrl.settlement, layoutConfig, result);
		};
		
		ctrl.partyCountryChanged = function(payParty){
			settlementPaymentService.partyCountryChanged(ctrl.settlement, payParty);
		};
		
		ctrl.partyStateChanged = function(payParty){
			settlementPaymentService.partyStateChanged(ctrl.settlement, payParty);
		};
		
		ctrl.close = function() {
			if (!dialogsModule.btnCallback || !dialogsModule.btnCallback["close"] || dialogsModule.btnCallback["close"]() !== false) {
				$uibModalInstance.dismiss();
			}
		};
	}
})(angular);
